package com.fangcang.thread;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.integration.util.CallerBlocksPolicy;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

@Configuration
public class MyThreadPoolConfig {
	
	@Bean
	public TaskExecutor taskExecutor() {
		ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
		taskExecutor.setCorePoolSize(1);
		taskExecutor.setMaxPoolSize(2);
		taskExecutor.setKeepAliveSeconds(600);
		taskExecutor.setQueueCapacity(5);
		//阻塞一定时间尝试添加，如果添加失败，直接抛异常
		taskExecutor.setRejectedExecutionHandler(new CallerBlocksPolicy(500));
		//丢弃队列中第一个任务，然后将任务添加到最后
//		taskExecutor.setRejectedExecutionHandler(new DiscardOldestPolicy());
//		//丢弃当前任务，不处理
//		taskExecutor.setRejectedExecutionHandler(new DiscardPolicy());
//		//丢弃当前任务，并抛RejectedExecutionException异常
//		taskExecutor.setRejectedExecutionHandler(new AbortPolicy());
		return taskExecutor;
	}
	
	@Bean
	public TaskExecutor  threadPoolTaskScheduler() {
		ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
		taskScheduler.setPoolSize(5);
		//优雅shut down
		taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
		taskScheduler.setThreadNamePrefix("Scheduler");
		
		return taskScheduler;
	}

}
